package orm

import (
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

// 实体之间外键关联: 1 v 1
type Dept struct {
	// 继承 gorm中的 Model
	gorm.Model
	Name string
	// autoCreateTime | autoUpdateTime 自动插入时间戳
	Version time.Time `gorm:"autoCreateTime"`
}

type Employee struct {
	gorm.Model
	Name   string
	Age    int
	Dept   Dept `gorm:"foreignKey:DeptId"`
	DeptId uint // 指定外键
}

var db2 *gorm.DB

func init() {
	dsn := "root:root@tcp(localhost:3306)/go_db?charset=utf8mb4&parseTime=true"
	db1, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic("failed to connect database")
	}
	db2 = db1
}

func main_8() {
	// 创建外键表
	// db2.AutoMigrate(&Dept{}, &Employee{})
	insert()
}

func insert() {
	// Create
	db2.Create(&Employee{Name: "里斯", Age: 12,
		Dept: Dept{Name: "ceshi"}})
}
